package com.team06.login.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.team06.login.entity.Role;
import com.team06.login.entity.User;
import com.team06.login.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@EnableTransactionManagement
public class SecurityConfig {

    private final UserServiceImpl userService;
    private final ObjectMapper objectMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    public SecurityConfig(UserServiceImpl userService, ObjectMapper objectMapper) {
        this.userService = userService;
        this.objectMapper = objectMapper;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable())
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                .authorizeHttpRequests(auth -> auth
                        // 公开访问的API
                        .requestMatchers("/api/auth/login").permitAll()
                        .requestMatchers("/api/auth/register").permitAll()
                        .requestMatchers("/api/auth/forgot-password").permitAll()
                        .requestMatchers("/api/auth/reset-password").permitAll()
                        .requestMatchers("/flightUpdate/**").permitAll()
                        // FlightSearchController中的所有接口需要认证
                        .requestMatchers("/flight/**").authenticated()

                        // 其他API需要认证
                        .anyRequest().authenticated()
                )
                .formLogin(form -> form
                        .loginProcessingUrl("/api/auth/login")
                        .usernameParameter("username")
                        .passwordParameter("password")
                        .successHandler(jsonAuthSuccessHandler())
                        .failureHandler(jsonAuthFailureHandler())
                        .permitAll()
                )
                .logout(logout -> logout
                        .logoutUrl("/api/auth/logout")
                        .logoutSuccessHandler((request, response, authentication) -> {
                            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                            response.getWriter().write("{\"code\":200,\"message\":\"登出成功\"}");
                        })
                );
        return http.build();
    }

    private AuthenticationSuccessHandler jsonAuthSuccessHandler() {
        return (req, res, auth) -> {
            User user = (User) auth.getPrincipal();

            // 调试日志
            System.out.println("认证成功用户: " + user.getUsername());
            System.out.println("用户角色: " + user.getAuthorities());

            // 构建前端期望的响应格式
            Map<String, Object> response = new HashMap<>();
            response.put("token", "generated-jwt-token"); // 实际项目替换为真实Token

            // 角色列表（确保与前端检查的格式一致）
            List<String> roles = user.getRoles().stream()
                    .map(Role::getName)
                    .map(String::toLowerCase) // 统一转为小写
                    .collect(Collectors.toList());
            response.put("roles", roles);

            // 可选：添加用户信息
            response.put("username", user.getUsername());

            res.setContentType(MediaType.APPLICATION_JSON_VALUE);
            res.getWriter().write(objectMapper.writeValueAsString(response));
        };
    }

    private AuthenticationFailureHandler jsonAuthFailureHandler() {
        return (req, res, ex) -> {
            res.setStatus(HttpStatus.UNAUTHORIZED.value());
            res.setContentType(MediaType.APPLICATION_JSON_VALUE);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 401);
            response.put("message", "用户名或密码错误");

            res.getWriter().write(objectMapper.writeValueAsString(response));
        };
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // 添加前端开发服务器端口(8081)
        configuration.setAllowedOrigins(Arrays.asList(
                "http://localhost:8080",
                "http://localhost:8081"  // 添加这一行
        ));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        configuration.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }}